// 电商管理后台系统主脚本

// 业务模块定义
const ecommerceAdmin = {
  productCatalog: "商品目录管理",
  inventory: "库存管理",
  orders: "订单处理流程",
  customers: "客户管理",
  promotions: "促销活动配置",
  analytics: "业务数据分析"
};

// 确保各模块在window对象上可用
window.ecommerceAdmin = ecommerceAdmin;

// 商品数据结构示例
const productSchema = {
  id: "唯一标识",
  name: "商品名称",
  variants: [
    {
      sku: "SKU编码",
      attributes: { color: "红色", size: "M" },
      price: 99.9,
      stock: 100
    }
  ],
  categories: ["分类1", "分类2"],
  status: "上架/下架"
};

// 订单状态机定义
const orderStatusMachine = {
  states: {
    PENDING: { label: "待付款", next: ["PAID", "CANCELLED"] },
    PAID: { label: "已付款", next: ["SHIPPED", "REFUNDED"] },
    SHIPPED: { label: "已发货", next: ["DELIVERED", "RETURNED"] },
    DELIVERED: { label: "已送达", next: ["COMPLETED"] },
    COMPLETED: { label: "已完成", next: [] },
    CANCELLED: { label: "已取消", next: [] },
    REFUNDED: { label: "已退款", next: [] },
    RETURNED: { label: "已退货", next: [] }
  },
  // 检查状态转换是否有效
  canTransition: function(from, to) {
    const currentState = this.states[from];
    return currentState && currentState.next.includes(to);
  },
  // 获取状态的中文标签
  getStateLabel: function(state) {
    return this.states[state] ? this.states[state].label : "未知状态";
  }
};

// 模拟数据生成函数
function generateMockData() {
  const mockData = {
    products: [],
    orders: [],
    customers: [],
    promotions: []
  };

  // 生成模拟商品数据
  const productNames = [
    "iPhone 15 Pro Max", "Samsung Galaxy S24 Ultra", "MacBook Pro 16", "AirPods Pro 2",
    "Sony WH-1000XM5", "Dell XPS 13", "iPad Air 5", "Surface Pro 9",
    "Apple Watch Series 9", "Google Pixel 8 Pro", "Lenovo ThinkPad X1", "ASUS ROG Zephyrus"
  ];
  const categories = ["电子产品", "服装鞋帽", "食品饮料", "家居日用"];
  const statuses = ["上架", "下架"];
  
  for (let i = 1; i <= 50; i++) {
    const variants = [];
    const colors = ["黑色", "白色", "红色", "蓝色", "绿色"];
    const storageOptions = ["128GB", "256GB", "512GB", "1TB"];
    
    // 为每个商品生成多个SKU变体
    for (let j = 0; j < Math.floor(Math.random() * 3) + 1; j++) {
      const color = colors[Math.floor(Math.random() * colors.length)];
      const storage = storageOptions[Math.floor(Math.random() * storageOptions.length)];
      const basePrice = Math.floor(Math.random() * 9000) + 1000;
      const priceMultiplier = storageOptions.indexOf(storage) * 0.2 + 1;
      
      variants.push({
        sku: `SKU-${i}-${j+1}`,
        attributes: { color: color, storage: storage },
        price: Math.round(basePrice * priceMultiplier * 100) / 100,
        stock: Math.floor(Math.random() * 1000)
      });
    }
    
    mockData.products.push({
      id: `P${String(i).padStart(6, '0')}`,
      name: productNames[Math.floor(Math.random() * productNames.length)],
      variants: variants,
      categories: [categories[Math.floor(Math.random() * categories.length)]],
      status: statuses[Math.floor(Math.random() * statuses.length)],
      created: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
    });
  }

  // 生成模拟客户数据
  const firstNames = ["张", "李", "王", "刘", "陈", "杨", "赵", "黄", "周", "吴"];
  const lastNames = ["伟", "芳", "娜", "秀英", "敏", "静", "强", "磊", "军", "洋"];
  
  for (let i = 1; i <= 100; i++) {
    const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
    const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];
    const orderCount = Math.floor(Math.random() * 20);
    
    mockData.customers.push({
      id: `C${String(i).padStart(6, '0')}`,
      name: firstName + lastName,
      email: `${firstName}${lastName}${i}@example.com`,
      phone: `13${Math.floor(Math.random() * 900000000 + 100000000)}`,
      registerDate: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      orderCount: orderCount,
      totalSpent: orderCount * Math.floor(Math.random() * 2000 + 100)
    });
  }

  // 生成模拟订单数据
  const statusKeys = Object.keys(orderStatusMachine.states);
  
  for (let i = 1; i <= 200; i++) {
    const customerIndex = Math.floor(Math.random() * mockData.customers.length);
    const productCount = Math.floor(Math.random() * 5) + 1;
    const orderProducts = [];
    let totalAmount = 0;
    
    for (let j = 0; j < productCount; j++) {
      const productIndex = Math.floor(Math.random() * mockData.products.length);
      const product = mockData.products[productIndex];
      const variantIndex = Math.floor(Math.random() * product.variants.length);
      const variant = product.variants[variantIndex];
      const quantity = Math.floor(Math.random() * 5) + 1;
      const subtotal = variant.price * quantity;
      
      orderProducts.push({
        productId: product.id,
        productName: product.name,
        variant: variant,
        quantity: quantity,
        subtotal: subtotal
      });
      
      totalAmount += subtotal;
    }
    
    mockData.orders.push({
      id: `O${String(i).padStart(8, '0')}`,
      customer: mockData.customers[customerIndex],
      products: orderProducts,
      totalAmount: Math.round(totalAmount * 100) / 100,
      status: statusKeys[Math.floor(Math.random() * statusKeys.length)],
      createdAt: new Date(Date.now() - Math.random() * 14 * 24 * 60 * 60 * 1000).toISOString(),
      updatedAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString()
    });
  }

  // 生成模拟促销活动数据
  const promotionTypes = ["满减", "折扣", "优惠券", "秒杀", "限时抢购"];
  const promotionStatuses = ["未开始", "进行中", "已结束"];
  
  for (let i = 1; i <= 20; i++) {
    const startDate = new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000);
    const endDate = new Date(startDate.getTime() + Math.random() * 30 * 24 * 60 * 60 * 1000);
    const now = new Date();
    let status = "未开始";
    
    if (startDate <= now && endDate >= now) {
      status = "进行中";
    } else if (endDate < now) {
      status = "已结束";
    }
    
    mockData.promotions.push({
      id: `Promo${String(i).padStart(4, '0')}`,
      name: promotionTypes[Math.floor(Math.random() * promotionTypes.length)] + "活动" + i,
      type: promotionTypes[Math.floor(Math.random() * promotionTypes.length)],
      startDate: startDate.toISOString(),
      endDate: endDate.toISOString(),
      status: status,
      description: "这是一个" + promotionTypes[Math.floor(Math.random() * promotionTypes.length)] + "促销活动"
    });
  }

  return mockData;
}

// 数据存储管理
class DataManager {
  constructor() {
    // 初始化模拟数据
    this.data = generateMockData();
    // 将数据存储到localStorage，实现持久化
    this.saveToStorage();
  }
  
  // 保存数据到localStorage
  saveToStorage() {
    localStorage.setItem('ecommerceAdminData', JSON.stringify(this.data));
  }
  
  // 从localStorage加载数据
  loadFromStorage() {
    const savedData = localStorage.getItem('ecommerceAdminData');
    if (savedData) {
      this.data = JSON.parse(savedData);
    } else {
      this.data = generateMockData();
      this.saveToStorage();
    }
  }
  
  // 获取商品列表（支持分页和筛选）
  getProducts(filters = {}, page = 1, pageSize = 10) {
    let filteredProducts = [...this.data.products];
    
    // 应用筛选条件
    if (filters.name) {
      filteredProducts = filteredProducts.filter(p => 
        p.name.toLowerCase().includes(filters.name.toLowerCase())
      );
    }
    if (filters.category) {
      filteredProducts = filteredProducts.filter(p => 
        p.categories.includes(filters.category)
      );
    }
    if (filters.status) {
      filteredProducts = filteredProducts.filter(p => p.status === filters.status);
    }
    
    // 计算分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedProducts = filteredProducts.slice(startIndex, endIndex);
    
    return {
      products: paginatedProducts,
      total: filteredProducts.length,
      page: page,
      pageSize: pageSize,
      totalPages: Math.ceil(filteredProducts.length / pageSize)
    };
  }
  
  // 获取订单列表（支持分页和筛选）
  getOrders(filters = {}, page = 1, pageSize = 10) {
    let filteredOrders = [...this.data.orders];
    
    // 应用筛选条件
    if (filters.orderId) {
      filteredOrders = filteredOrders.filter(o => o.id.includes(filters.orderId));
    }
    if (filters.customerName) {
      filteredOrders = filteredOrders.filter(o => 
        o.customer.name.includes(filters.customerName)
      );
    }
    if (filters.status) {
      filteredOrders = filteredOrders.filter(o => o.status === filters.status);
    }
    
    // 按创建时间倒序排序
    filteredOrders.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    
    // 计算分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedOrders = filteredOrders.slice(startIndex, endIndex);
    
    return {
      orders: paginatedOrders,
      total: filteredOrders.length,
      page: page,
      pageSize: pageSize,
      totalPages: Math.ceil(filteredOrders.length / pageSize)
    };
  }
  
  // 添加新商品
  addProduct(product) {
    const newProduct = {
      ...product,
      id: `P${String(this.data.products.length + 1).padStart(6, '0')}`,
      created: new Date().toISOString()
    };
    this.data.products.push(newProduct);
    this.saveToStorage();
    return newProduct;
  }
  
  // 更新订单状态
  updateOrderStatus(orderId, newStatus) {
    const order = this.data.orders.find(o => o.id === orderId);
    if (order && orderStatusMachine.canTransition(order.status, newStatus)) {
      order.status = newStatus;
      order.updatedAt = new Date().toISOString();
      this.saveToStorage();
      return true;
    }
    return false;
  }
  
  // 数据导出功能
  exportToCSV(data, filename) {
    // 检查数据是否为空
    if (!data || !data.length) {
      console.error('没有数据可以导出');
      return;
    }
    
    // 获取所有可能的列标题
    const headers = Object.keys(data[0]);
    
    // 构建CSV内容
    let csvContent = '\uFEFF'; // 添加BOM以支持中文
    
    // 添加表头
    csvContent += headers.map(header => {
      // 将英文键转换为中文显示
      const headerMap = {
        'id': 'ID',
        'name': '名称',
        'price': '价格',
        'stock': '库存',
        'status': '状态',
        'createdAt': '创建时间',
        'updatedAt': '更新时间',
        'totalAmount': '总金额',
        'email': '邮箱',
        'phone': '电话',
        'registerDate': '注册日期',
        'orderCount': '订单数',
        'totalSpent': '消费总额',
        'type': '类型',
        'startDate': '开始日期',
        'endDate': '结束日期',
        'description': '描述'
      };
      return `"${headerMap[header] || header}"`;
    }).join(',') + '\n';
    
    // 添加数据行
    data.forEach(item => {
      csvContent += headers.map(header => {
        let value = item[header];
        // 格式化日期
        if (value && (header.includes('Date') || header.includes('At'))) {
          value = new Date(value).toLocaleString('zh-CN');
        }
        // 处理对象类型
        if (typeof value === 'object' && value !== null) {
          value = JSON.stringify(value);
        }
        // 确保值被引号包围，处理包含逗号的值
        return `"${String(value).replace(/"/g, '""')}"`;
      }).join(',') + '\n';
    });
    
    // 创建Blob并下载
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    link.setAttribute('href', url);
    link.setAttribute('download', filename || 'export.csv');
    link.style.visibility = 'hidden';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}

// 初始化数据管理器
const dataManager = new DataManager();

// DOM工具函数
const DOM = {
  // 选择元素
  $: (selector) => document.querySelector(selector),
  $$: (selector) => document.querySelectorAll(selector),
  
  // 创建元素
  create: (tagName, className = '', attributes = {}) => {
    const element = document.createElement(tagName);
    if (className) element.className = className;
    Object.entries(attributes).forEach(([key, value]) => {
      element.setAttribute(key, value);
    });
    return element;
  },
  
  // 显示元素
  show: (element) => {
    if (typeof element === 'string') {
      element = DOM.$(element);
    }
    if (element) element.style.display = '';
  },
  
  // 隐藏元素
  hide: (element) => {
    if (typeof element === 'string') {
      element = DOM.$(element);
    }
    if (element) element.style.display = 'none';
  },
  
  // 添加事件监听
  on: (element, event, callback) => {
    if (typeof element === 'string') {
      element = DOM.$(element);
    }
    if (element) element.addEventListener(event, callback);
  },
  
  // 切换类
  toggleClass: (element, className) => {
    if (typeof element === 'string') {
      element = DOM.$(element);
    }
    if (element) element.classList.toggle(className);
  }
};

// 视图切换管理
class ViewManager {
  constructor() {
    this.currentView = 'dashboard';
    this.views = DOM.$$('.view');
  }
  
  // 切换到指定视图
  switchTo(viewId) {
    // 隐藏所有视图
    this.views.forEach(view => {
      view.classList.remove('active');
    });
    
    // 显示指定视图
    const targetView = DOM.$(`#${viewId}-view`);
    if (targetView) {
      targetView.classList.add('active');
      this.currentView = viewId;
      
      // 根据视图ID初始化相应的模块
      switch(viewId) {
        case 'dashboard':
          if (window.dashboard) dashboard.init();
          break;
        case 'products':
          if (window.products) products.init();
          break;
        case 'inventory':
          if (window.inventory) inventory.init();
          break;
        case 'orders':
          if (window.orders) orders.init();
          break;
        case 'customers':
          if (window.customers) customers.init();
          break;
        case 'promotions':
          if (window.promotions) promotions.init();
          break;
        case 'analytics':
          if (window.analytics) analytics.init();
          break;
      }
      
      // 触发视图切换事件
      const event = new CustomEvent('viewChanged', {
        detail: { viewId: viewId }
      });
      document.dispatchEvent(event);
    }
  }
}

// 初始化视图管理器
const viewManager = new ViewManager();

// 导出全局对象
window.ecommerceAdmin = ecommerceAdmin;
window.productSchema = productSchema;
window.orderStatusMachine = orderStatusMachine;
window.dataManager = dataManager;
window.DOM = DOM;
window.viewManager = viewManager;

// 页面加载完成后执行
DOM.on(window, 'load', () => {
  console.log('电商管理后台系统已加载');
  
  // 从localStorage加载数据
  dataManager.loadFromStorage();
});